package com.zbkj.client.controller;

import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.ClientProductService;
import com.zbkj.common.model.assets.ClientProduct;
import com.zbkj.common.model.assets.Material;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.request.client.ClientProductAddRequest;
import com.zbkj.common.request.client.BatchDeleteRequest;
import com.zbkj.common.exception.CrmebException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/api/client/assets")
@Api(tags = "客户端产品管理")
public class ClientProductController {

    @Autowired
    private ClientProductService clientProductService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @ApiOperation(value = "批量删除产品（软删除）")
    @PostMapping("/delProduct")
    public CommonResult<Map<String, Object>> delProduct(@RequestBody BatchDeleteRequest request, HttpServletRequest httpRequest) {
        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return CommonResult.failed("请选择要删除的产品");
        }
        
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        // 校验所有id对应的记录
        for (Integer id : ids) {
            ClientProduct product = clientProductService.getById(id);
            if (product == null || product.getIsDel() == null || product.getIsDel() != 0) {
                return CommonResult.failed("产品ID " + id + " 不存在或已被删除");
            }
            if (!userId.equals(product.getUserId())) {
                return CommonResult.failed("无权操作产品ID " + id);
            }
        }

        boolean result = clientProductService.batchDelProduct(ids);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result ? 1 : 0);
        return CommonResult.success(data);
    }

    @ApiOperation(value = "获取产品列表")
    @GetMapping("/listProduct")
    public CommonResult<List<ClientProduct>> listProduct(@RequestParam(value = "parentId", required = false) Integer parentId, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        if (parentId != null && parentId != 0) {
            ClientProduct parent = clientProductService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权查看该文件夹");
            }
        }
        List<ClientProduct> list = clientProductService.listProduct(userId, parentId);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "根据ID获取产品详情")
    @GetMapping("/getProduct")
    public CommonResult<ClientProduct> getProduct(@RequestParam("id") Integer id, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        if (id == null) {
            return CommonResult.failed("产品ID不能为空");
        }
        
        ClientProduct product = clientProductService.getById(id);
        if (product == null) {
            return CommonResult.failed("产品不存在");
        }
        
        if (product.getIsDel() == null || product.getIsDel() != 0) {
            return CommonResult.failed("产品已被删除");
        }
        
        if (!userId.equals(product.getUserId())) {
            return CommonResult.failed("无权查看该产品");
        }
        
        return CommonResult.success(product);
    }

    @ApiOperation(value = "添加产品")
//    @PostMapping(value = "/addProduct", consumes = "multipart/form-data")
    @PostMapping(value = "/addProduct")
    public CommonResult<Map<String, Object>> addProduct(@RequestBody ClientProductAddRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        Integer parentId = request.getParentId();
        if (parentId != null && parentId != 0) {
            ClientProduct parent = clientProductService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权操作");
            }
            if (parent.getIsFolder() == null || parent.getIsFolder() == 0) {
                return CommonResult.failed("请在文件夹下操作");
            }
        }

        String token = httpRequest.getHeader("token");
        Integer merId = 0;
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        if (userInfo != null) {
            merId = userInfo.getMerId();
        }
        ClientProduct result = clientProductService.addClientProduct(request, userId, merId);
        if (result == null) {
            return CommonResult.failed("添加产品失败，请检查参数");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("result", 1);
        return CommonResult.success(data);
    }

    @ApiOperation(value = "编辑产品")
    @PostMapping(value = "/editProduct")
    public CommonResult<Map<String, Object>> editProduct(@RequestBody ClientProductAddRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        if (request.getId() == null) {
            return CommonResult.failed("产品ID不能为空");
        }
        
        try {
            boolean result = clientProductService.editProduct(request, userId);
            Map<String, Object> data = new HashMap<>();
            data.put("result", result ? 1 : 0);
            return CommonResult.success(data);
        } catch (CrmebException e) {
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            return CommonResult.failed("编辑产品失败");
        }
    }

} 